#include "Space2D.h"
#include "Dot.h"
#include <QDebug>
#include <Logger.h>

Space2D::Space2D(QWidget *parent) :
    QWidget(parent)
{
    painter = new QPainter;
    pen = new QPen(Qt::black, 2, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin);
    m_lastSelectedTexture = 0;
    m_LeftMouseClick = false;
    m_RightMouseClick = false;
    m_NumControlPoints = 0;

    this->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
}

Space2D::~Space2D()
{
    delete painter;
    delete pen;
    foreach(Drawing* draw, draws){
        delete draw;
    }
}

void Space2D::addDraws(QList<Drawing*> drawsSet)
{
    draws.append(drawsSet);
    this->update();
}

void Space2D::addDraw(Drawing* draw)
{
    draws.append(draw);
    this->update();
}

void Space2D::cleanAll()
{
    draws.clear();
    this->update();
}

void Space2D::paintEvent(QPaintEvent*)
{

    painter->begin(this);
    painter->setPen(*pen);

    foreach(Drawing* draw, draws)
    {
        draw->draw(painter);
    }

    painter->end();
}

void Space2D::mousePressEvent ( QMouseEvent * e )
{

    //Add point event.
    if ( e->button() == Qt::LeftButton && (m_NumControlPoints > 0) )
    {
        m_LeftMouseClick = true;
        m_lastAddPoint = e->pos();
        QPoint* point = new QPoint(m_lastAddPoint);
        m_LastVertexs.append(point);
        Dot* dot = new Dot(point,m_LastDraw->colors().at(initialNumControlPoints() - numControlPoints()));
        addDraw(dot);
        m_NumControlPoints--;
    }
}

void Space2D::mouseReleaseEvent ( QMouseEvent * e )
{

    if ( e->button() == Qt::LeftButton && m_LeftMouseClick)
    {
        m_LeftMouseClick = false;
        if (m_NumControlPoints == 0)
        {
            m_LastDraw->setVertexs(m_LastVertexs);
            m_LastVertexs.clear();
            if (lastSelectedTexture())
            {
                m_LastDraw->setTexture(new Texture(lastSelectedTexture()));
            }
            addDraw(m_LastDraw);
            m_LastDraw = 0;
            m_lastSelectedTexture = 0;
        }
    }
    if ( e->button() == Qt::RightButton && m_RightMouseClick) m_RightMouseClick = false;
}

int Space2D::numControlPoints()
{
    return m_NumControlPoints;
}

void Space2D::setNumControlPoints(int num)
{
    m_NumControlPoints = num;
}

void Space2D::setLastDraw(Drawing* lastDraw)
{
    m_LastDraw = lastDraw;
}

int Space2D::initialNumControlPoints()
{
    return m_initialNumControlPoints;
}

void Space2D::setInitialNumControlPoints(int initialNumControlPoints)
{
    m_initialNumControlPoints = initialNumControlPoints;
}

QImage* Space2D::lastSelectedTexture()
{
    return m_lastSelectedTexture;
}

void Space2D::setLastSelectedTexture(QImage* texture)
{
    m_lastSelectedTexture = texture;
}
